package link

import (
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

func ExtractLinks(seed string) ([]string, error) {
	var urls []string

	pattern := regexp.MustCompile(`<a\b[^>]+\bhref="([^"]*)"[^>]*>[\s\S]*?</a>`)
	resp, err := http.Get(seed)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	res := pattern.FindAllStringSubmatch(string(buf), -1)

	for _, e := range res {
		if len(e) != 2 {
			continue
		}
		if strings.HasPrefix(e[1], "http") {
			urls = append(urls, e[1])
		}
	}
	return urls, nil
}
